package com.xuyuan.mybatis;

import com.xuyuan.agent.entity.Student;
import com.xuyuan.mybatis.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * mybatis入门案例
 *
 * @author xuyuan
 */
public class Demo {

    /**
     * 1、加载配置获取SqlSessionFactory
     * 2、构造者创建SqlSession
     * 3、使用SqlSession执行sql
     * 4、获取结果集
     * 5、关闭SqlSession
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis/dev-mybatis-config.xml");
        // 创建一个sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // List<Integer> list = new ArrayList<>();
        // for (int i = 0; i < 1000000; i++) {
        //     list.add(i);
        // }
        // List<String> result = sqlSession.selectList("com.xuyuan.mybatis.mapper.StudentMapper.snowflake", list);
        // List<String> collect = result.stream().collect(Collectors.groupingBy(p -> p)).values().stream().filter(lll -> lll.size() > 1).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        // System.out.println(collect.size());

        Student student = sqlSession.selectOne("com.xuyuan.mybatis.mapper.StudentMapper.selectById", "1");
        System.out.println(student);

        // 使用最原始方式： namespace.statementid 执行
        List<Student> objects = sqlSession.selectList("com.xuyuan.mybatis.mapper.StudentMapper.selectAll");
        objects.stream().forEach(System.out::println);

        // 使用mapper映射器接口方式执行
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectAll();
        students.stream().forEach(System.out::println);
    }

}
